package com.yenlien.traceyun.plant.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.yenlien.traceyun.business.service.rest.usercenter.FileRestService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Date 2022/8/31
 * @Author jiaLong
 * @Descript EasyExcel实现一个单元格导出多张图片
 */
@Component
//public class ListImgConverter implements Converter<List<URL>> {
public class ListImgConverter implements Converter<String> {

//    @Autowired
    private FileRestService fileRestService = BeanUtil.getBean(FileRestService.class);

    @Override
    public Class supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        /**
         *这里记得枚举类型为IMAGE
         */
        return CellDataTypeEnum.IMAGE;
    }

    @Override
    public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
//    public CellData convertToExcelData(List<URL> value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
    public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        // 这里进行对数据实体类URL集合处理
        List<CellData> data = new ArrayList<>();
//        for (URL url : value) {
//            InputStream inputStream = null;
//            try {
//                //
//                inputStream = url.openStream();
//                byte[] bytes = IoUtils.toByteArray(inputStream);
//                data.add(new CellData(bytes));
//                // 如果是单张图片就  return new CellData(bytes);
//            } catch (Exception e) {
//                throw new IOException("导出excel图片读取异常");
//            } finally {
//                if (inputStream != null){
//                    inputStream.close();
//                }
//            }
//        }
        String[] splitList = value.split(";");
        for(String img : splitList){
            byte[] show = fileRestService.show(img, null);
            if(Objects.nonNull(show)){
                data.add(new CellData(show));
            }
        }
        // 这种方式并不能返回一个List,所以只好通过CellData cellData = new CellData(data);将这个list对象塞到返回值CellData对象的data属性中；
        CellData cellData = new CellData(data);
        cellData.setType(CellDataTypeEnum.IMAGE);
        return cellData;
    }

}
